package info.batcloud.fanli.api.interceptor;

import info.batcloud.fanli.api.exception.UserLevelRequireException;
import info.batcloud.fanli.api.security.annotation.UserLevelRequire;
import info.batcloud.fanli.core.enums.UserLevel;
import info.batcloud.fanli.core.helper.SecurityHelper;
import info.batcloud.fanli.core.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserLevelInterceptor extends HandlerInterceptorAdapter {

    @Inject
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            UserLevelRequire authorizeRequire = ((HandlerMethod) handler).getMethodAnnotation(UserLevelRequire.class);

            if (authorizeRequire != null) {
                long userId = SecurityHelper.loginUserId();
                UserLevel userLevel = userService.findUserLevelByUserId(userId);
                if (userLevel.level < authorizeRequire.value().level) {
                    throw new UserLevelRequireException(authorizeRequire.value());
                }
            }
        }
        return super.preHandle(request, response, handler);
    }
}
